package org.jeecg.modules.hotel.arrangement.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.util.concurrent.AtomicDouble;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javafx.css.Styleable;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.demo.bed.entity.LwgyBaseBed;
import org.jeecg.modules.basic.demo.bed.entity.LwgyBedAssignment;
import org.jeecg.modules.basic.demo.bed.mapper.LwgyBaseBedMapper;
import org.jeecg.modules.basic.demo.bed.service.ILwgyBaseBedService;
import org.jeecg.modules.basic.demo.student.entity.LwgyBaseStudent;
import org.jeecg.modules.basic.demo.student.service.ILwgyBaseStudentService;
import org.jeecg.modules.basic.iouser.controller.LwgyInoutUserController;
import org.jeecg.modules.hotel.arrangement.entity.*;
import org.jeecg.modules.hotel.arrangement.service.AutoAssignService;
import org.jeecg.modules.hotel.arrangement.service.ILwgyHotelArrangementService;
import org.jeecg.modules.hotel.arrangement.util.ExcelImport;
import org.jeecg.modules.hotel.arrangement.util.ExcelImports;
import org.jeecg.modules.hotel.history.entity.LwgyHotelHistory;
import org.jeecg.modules.hotel.history.mapper.LwgyHotelHistoryMapper;
import org.jeecg.modules.hotel.history.service.ILwgyHotelHistoryService;
import org.jeecg.modules.hotel.requisition.entity.LwgyHotelRequisition;
import org.jeecg.modules.hotel.requisition.service.ILwgyHotelRequisitionService;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.StandardSocketOptions;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Description: 住宿分配管理
 * @Author: Aioe
 * @Date: 2021-02-24
 * @Version: V1.0
 */

@Api(tags = "住宿分配管理")
@RestController
@RequestMapping("/hotel/lwgyHotelArrangement")
@Slf4j
public class LwgyHotelArrangementController extends JeecgController<LwgyHotelArrangement, ILwgyHotelArrangementService> {

    @Autowired
    private ILwgyHotelArrangementService lwgyHotelArrangementService;

    @Autowired
    private ILwgyHotelHistoryService lwgyHotelHistoryService;

    @Autowired
    private ILwgyBaseBedService lwgyBaseBedService;

    @Autowired
    private ILwgyBaseStudentService lwgyBaseStudentService;

    @Resource
    private LwgyBaseBedMapper lwgyBaseBedMapper;

    @Resource
    private LwgyHotelHistoryMapper lwgyHotelHistoryMapper;

    @Autowired
    private LwgyInoutUserController lwgyInoutUserController;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    private ILwgyHotelRequisitionService lwgyHotelRequisitionService;

    @Autowired
    private AutoAssignService autoAssignService;

    /**
     * 调宿
     *
     */
    @AutoLog(value = "调宿")
    @ApiOperation(value = "调宿", notes = "调宿")
    @PutMapping(value = "/updateBedStu")
    public Result<?> updateBedStu(@RequestBody LwgyHotelArrangement lwgyHotelArrangement) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = sysUser.getUsername();
        List<String> roles = sysBaseAPI.getRolesByUsername(username);

 /*       if(roles.contains("fdy")){
            String studentId = lwgyHotelArrangement.getStudentId();
            LwgyBaseStudent student = lwgyBaseStudentService.getById(studentId);

            LwgyHotelRequisition lwgyHotelRequisition = new LwgyHotelRequisition();
            lwgyHotelRequisition.setAuditProcess("2");
            lwgyHotelRequisition.setFromUser(username);
            lwgyHotelRequisition.setToUser("admin");
            LwgyBaseBed lwgyBaseBed ;
            if(lwgyHotelArrangement.getBehavior().equals("choose_bed")){//如果是入住
                lwgyBaseBed = lwgyBaseBedService.getById(lwgyHotelArrangement.getAfterBed());
                lwgyHotelRequisition.setBedId(lwgyHotelArrangement.getAfterBed());
            }else {
                lwgyBaseBed = lwgyBaseBedService.getById(lwgyHotelArrangement.getBeforeBed());
                lwgyHotelRequisition.setBedId(lwgyHotelArrangement.getBeforeBed());
                lwgyHotelRequisition.setAfterBed(lwgyHotelArrangement.getAfterBed());
            }
            lwgyHotelRequisition.setUnitId(lwgyBaseBed.getRoomId());
            lwgyHotelRequisition.setStudentId(studentId);
            lwgyHotelRequisition.setProcessingState("0");
            lwgyHotelRequisition.setReason("辅导员请求审核!");
            lwgyHotelRequisition.setBehavioral(lwgyHotelArrangement.getBehavior());
//            lwgyHotelRequisition.setReason();
            lwgyHotelRequisition.setRoomsex(student.getStudentSex());
            QueryWrapper<LwgyRoomViews> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("room_id",lwgyBaseBed.getRoomId());
            String buildingId = lwgyHotelArrangementService.getBuildId(lwgyBaseBed.getRoomId());
            lwgyHotelRequisition.setBuildingId(buildingId);
            lwgyHotelRequisition.setStudentCampus(student.getStudentCampus());
            lwgyHotelRequisition.setStudentCollege(student.getStudentCollege());
            lwgyHotelRequisition.setStudentClass(student.getStudentClass());
            lwgyHotelRequisition.setStudentYear(student.getStudentYear());
            lwgyHotelRequisition.setStudentMajor(student.getStudentMajor());
            lwgyHotelRequisition.setStudentName(student.getStudentName());
            lwgyHotelRequisitionService.pushMsg(lwgyHotelRequisition,username,roles,student);
            lwgyHotelRequisitionService.save(lwgyHotelRequisition);

            //微信：
            lwgyHotelRequisitionService.pushWx(lwgyHotelRequisition,username,roles,student);
            return Result.OK("已将调宿信息推送给管理员",null);
        }*/

        String behavior = lwgyHotelArrangement.getBehavior();
        String type = "";
        String stuIdS = lwgyHotelArrangement.getStudentId();
        LwgyHotelRequisition lwgyHotel = lwgyHotelRequisitionService.getStuAdmin(stuIdS);
        //确认是调宿
        if (behavior.equals("change_bed")) {
            type = "调宿";
            lwgyHotelArrangement.setId(lwgyHotelArrangement.getAfterBed());
            lwgyHotelArrangement.setAdminId(lwgyHotel.getAdminName());
            //退掉之前的床位
            lwgyHotelArrangementService.checkOutStu(lwgyHotelArrangement);
            try {
                List<LwgyBaseBed> bed = lwgyBaseBedMapper.getBedIdList(lwgyHotelArrangement.getAfterBed(), "bed");
                lwgyInoutUserController.iouserChange(lwgyHotelArrangement.getStudentId(), bed.get(0).getBuildingId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        //如果行为是退宿
        } else if (behavior.equals("leave_bed")) {
            type = "退宿";
            //将变更之前的床位id给现在的id
            lwgyHotelArrangement.setId(lwgyHotelArrangement.getBeforeBed());
            lwgyHotelArrangementService.cleanBed(lwgyHotelArrangement.getBeforeBed());
        //如果行为是调宿或者入住
        } else {
            type = "入住";
            //将变更之后的床位id给现在的id
            lwgyHotelArrangement.setId(lwgyHotelArrangement.getAfterBed());
            lwgyHotelArrangement.setAdminId(lwgyHotel.getAdminName());
        }
        //辅导员调整宿舍，会给管理员推送消息
        if (roles.contains("fdy")) {
            lwgyHotelRequisitionService.pushChangeMsg(lwgyHotelArrangement, username, type);
        }
        lwgyHotelArrangementService.updateBedStu(lwgyHotelArrangement);
        LwgyHotelHistory lwgyHotelHistory = new LwgyHotelHistory();
        lwgyHotelHistory.setAfterBed(lwgyHotelArrangement.getAfterBed());
        lwgyHotelHistory.setBehavior(lwgyHotelArrangement.getBehavior());
        lwgyHotelHistory.setPersonId(lwgyHotelArrangement.getStudentId());
        lwgyHotelHistory.setBeforeBed(lwgyHotelArrangement.getBeforeBed());
        lwgyHotelHistory.setCreateTime(lwgyHotelArrangement.getUpdateTime());
        //保存历史记录
        lwgyHotelHistoryService.save(lwgyHotelHistory);
        return Result.OK("编辑成功!");
    }

    /**
     * 退宿
     *
     * @param lwgyHotelArrangement
     * @return
     */
    @AutoLog(value = "退宿")
    @ApiOperation(value = "退宿", notes = "退宿")
    @PutMapping(value = "/checkOutStuUrl")
    public Result<?> checkOutStu(@RequestBody LwgyHotelArrangement lwgyHotelArrangement) {
        System.out.println(lwgyHotelArrangement);
        //1. 退宿
        lwgyHotelArrangementService.checkOutStu(lwgyHotelArrangement);
        //2. 存储到历史记录
        LwgyHotelHistory lwgyHotelHistory = new LwgyHotelHistory();
        lwgyHotelHistory.setBeforeBed(lwgyHotelArrangement.getId());
        lwgyHotelHistory.setBehavior("leave_bed");
        lwgyHotelHistory.setPersonId(lwgyHotelArrangement.getStudentId());
        lwgyHotelHistory.setSort("");
        lwgyHotelHistoryService.save(lwgyHotelHistory);
        return Result.OK("编辑成功!");
    }

    /**
     * 批量退宿
     *
     * @param hotelArrangeList
     * @return
     */
    @AutoLog(value = "批量退宿")
    @ApiOperation(value = "批量退宿", notes = "批量退宿")
    @PutMapping(value = "/cleanBed")
    public Result<?> cleanBed(@RequestBody List<Map<String, String>> hotelArrangeList) {
        List<LwgyHotelHistory> arrangementList = new ArrayList<>();
        String ids = "";
        LwgyHotelHistory lwgyHotelHistory;
        for (Map<String, String> map : hotelArrangeList) {
            ids += map.get("beforeBed") + ",";
            lwgyHotelHistory = JSON.parseObject(JSON.toJSONString(map), LwgyHotelHistory.class);
            arrangementList.add(lwgyHotelHistory);
        }
        lwgyHotelArrangementService.cleanBed(ids);//批量清空住宿
        lwgyHotelHistoryService.saveBatch(arrangementList);//批量存储退宿记录
        return Result.OK("编辑成功!");
    }

    /**
     * 批量调宿、入住
     *
     * @param hotelArrangeList
     * @return
     */
    @AutoLog(value = "批量调宿、入住")
    @ApiOperation(value = "批量调宿、入住", notes = "批量调宿、入住")
    @PutMapping(value = "/batchUpdateBedStu")
    public Result<?> batchUpdateBedStu(@RequestBody List<Map<String, String>> hotelArrangeList) {
        List<LwgyHotelHistory> arrangementList = new ArrayList<>();
        String ids = "";
        String afterBed = "";
        LwgyBaseBed lwgyBaseBed;
        List<LwgyBaseBed> bedList = new ArrayList<>();
        LwgyHotelHistory lwgyHotelHistory;
        String behavior = hotelArrangeList.get(0).get("behavior");
        String stuIdS = hotelArrangeList.get(0).get("personId");
        //如果是调宿，需要先清空住宿信息
        if (behavior.equals("change_bed")) {
            for (Map<String, String> map : hotelArrangeList) {
                ids += map.get("beforeBed") + ",";
            }
            //批量清空原来的住宿信息
            lwgyHotelArrangementService.cleanBed(ids);
        }
        LwgyHotelRequisition lwgyHotel = lwgyHotelRequisitionService.getStuAdmin(stuIdS);
        for (Map<String, String> map : hotelArrangeList) {//
            lwgyBaseBed = new LwgyBaseBed();
            lwgyBaseBed.setId(map.get("afterBed"));
            lwgyBaseBed.setStudentId(map.get("personId"));
            lwgyBaseBed.setAdminId(lwgyHotel.getAdminName());
            bedList.add(lwgyBaseBed);
            lwgyHotelHistory = JSON.parseObject(JSON.toJSONString(map), LwgyHotelHistory.class);
            //创建历史记录实体的集合
            arrangementList.add(lwgyHotelHistory);
        }
        //更新入住信息
        lwgyBaseBedService.updateBatchById(bedList);
//        lwgyBaseBedService.saveBatch(bedList);
        //保存历史记录
        lwgyHotelHistoryService.saveBatch(arrangementList);
        return Result.OK("编辑成功!");
    }


    /**
     * 批量分配床位
     *
     * @param hotelArrangeList
     * @return
     */
    @AutoLog(value = "批量分配床位")
    @ApiOperation(value = "批量分配床位", notes = "批量分配床位")
    @PutMapping(value = "/batchAllot")
    public Result<?> batchAllot(@RequestBody Map<String, String> hotelArrangeList) {
        System.out.println("hotelArrangeList = " + hotelArrangeList);
        lwgyHotelArrangementService.batchAllot(hotelArrangeList);
        return Result.OK("操作成功!");
    }

    /**
     * 批量回收床位
     *
     * @param bedId
     * @return
     */
    @AutoLog(value = "批量回收床位")
    @ApiOperation(value = "批量回收床位", notes = "批量回收床位")
    @PutMapping(value = "/batchRecycle")
    public Result<?> batchRecycle(@RequestBody String bedId) {
        if(bedId.length() > 6){
            bedId = bedId.substring(10,bedId.length() - 3);
            lwgyHotelArrangementService.batchRecycle(bedId);
        }
        return Result.OK("操作成功!");
    }

    /**
     * 根据id获去权限，用于下发分配床位
     */
    @AutoLog(value = "根据id获去权限，用于下发分配床位")
    @ApiOperation(value = "根据id获去权限，用于下发分配床位", notes = "根据id获去权限，用于下发分配床位")
    @GetMapping(value = "/getPermissionById")
    public Result<?> getPermissionById(@RequestParam(name = "id") String id) {
        List<String> roles = lwgyBaseBedService.getRoleById(id);
        //角色是超级管理员
        if (roles.contains("admin")) {
            return Result.OK("1");
        //角色是校领导
        } else if (roles.contains("xld")) {
            return Result.OK("2");
        } else {
            return Result.OK(3);
        }
    }

    /**
     * 批量离校
     *
     * @param stuIds
     */
    @AutoLog(value = "批量离校")
    @ApiOperation(value = "批量离校", notes = "批量离校")
    @PostMapping(value = "/leaveSchool")
    public Result<?> leaveSchool(@RequestBody String stuIds) {
        if (oConvertUtils.isNotEmpty(stuIds)) {
            if (stuIds.length() > 11) {
                stuIds = stuIds.substring(11, stuIds.length() - 2);
                System.out.println(stuIds);
                // 批量离校
                lwgyHotelArrangementService.leaveSchool(stuIds);

                List<LwgyBaseBed> bedStuId = lwgyHotelArrangementService.selectStuBedByStuId(stuIds);
                    String ids = "";
                    LwgyHotelHistory lwgyHotelHistory;
                    List<LwgyHotelHistory> arrangementList = new ArrayList<>();
                    LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                    for (LwgyBaseBed item : bedStuId) {
                        ids += item.getId() + ",";
                        lwgyHotelHistory = JSON.parseObject(JSON.toJSONString(item), LwgyHotelHistory.class);
                        lwgyHotelHistory.setPersonId(item.getStudentId());
                        lwgyHotelHistory.setBeforeBed(item.getId());
                        lwgyHotelHistory.setBehavior("leave_bed");
                        lwgyHotelHistory.setCreateBy(sysUser.getUsername());
                        arrangementList.add(lwgyHotelHistory);

                    }
                    //批量清空住宿
                    lwgyHotelArrangementService.cleanBed(ids);
                    //批量存储退宿记录
                    lwgyHotelHistoryService.saveBatch(arrangementList);
                return Result.OK("编辑成功!");
            }
        }
        return Result.error("编辑失败!");
    }
    /**
     * 批量返校
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "批量返校")
    @ApiOperation(value = "批量返校", notes = "批量返校")
    @PostMapping(value = "/revertLeaveStu")
    public Result<?> revertLeaveStu(@RequestBody String ids) {
        if (oConvertUtils.isNotEmpty(ids)) {
            if (ids.length() > 11) {
                ids = ids.substring(8, ids.length() - 2);
                lwgyHotelArrangementService.revertLeaveStu(ids);
                return Result.OK("编辑成功!");
            }
        }
        return Result.error("错误！");
    }

    /**
     * 查询学生可选择的房间
     *
     * @param studentId
     * @return
     */
    @GetMapping("/studentChooseBedList")
    public Result<?> studentChooseBedList(@RequestParam(name = "studentId", required = false, defaultValue = "1385586453517447177") String studentId) {
//        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        String id = sysUser.getId();

        LwgyBaseStudent lwgyBaseStudent = lwgyBaseStudentService.getById(studentId);
        String studentClass = lwgyBaseStudent.getStudentClass();
        boolean b = lwgyHotelArrangementService.getClassOpenTime(studentClass);
        if (!b) {
            return new Result<>().error500("未到选房时间！");
        }
        LwgyBaseBed lwgyBaseBed = new LwgyBaseBed();
        lwgyBaseBed.setStudentClass(studentClass);
        lwgyBaseBed.setRoomSex(lwgyBaseStudent.getStudentSex());
        QueryWrapper<LwgyBaseBed> queryWrapper = QueryGenerator.initQueryWrapper(lwgyBaseBed, null);
        Page<LwgyBaseBed> page = new Page<>(0, 100);
        queryWrapper.orderByAsc("name");
        IPage<LwgyBaseBed> pageList = lwgyBaseBedService.queryPageListCustom(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 学生自选床位
     *
     * @param lwgyBaseBed
     * @return
     */
    @ApiOperation("学生自选床位")
    @PutMapping("/studentChooseBed")
    public Result<?> studentChooseBed(@RequestBody LwgyBaseBed lwgyBaseBed) {
        String lockKey = "choose_bed";
        String clientId = UUID.randomUUID().toString();
        Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, clientId, 30, TimeUnit.SECONDS);//redis分布式锁 30s 过期
        if (!result) {
            return Result.error("前方拥堵，请重试");
        }
        try {
            if (oConvertUtils.isEmpty(lwgyBaseBed.getId())) {
                return Result.error("未选择床位");
            }
            QueryWrapper<LwgyBaseBed> queryWrapper = new QueryWrapper();
            //根据学生id获取学生信息
            LwgyBaseStudent lwgyBaseStudent = lwgyBaseStudentService.getById(lwgyBaseBed.getStudentId());
            //获取学生的班级
            String studentClass = lwgyBaseStudent.getStudentClass();
            //查看该班级是否在选房时间段
            boolean b = lwgyHotelArrangementService.getClassOpenTime(studentClass);
            if (!b) {
                return Result.error("未到选房时间！");
            }
            //通过学生id查询缓存中是否存在他的床位信息
            Object o = redisUtil.get(lwgyBaseStudent.getId());
            //不为空
            if (oConvertUtils.isNotEmpty(o)) {
                return Result.error("已经选择过床位");
            } else {                                            //缓存中不存在该学生的床位信息  再查db
                queryWrapper.eq("student_id", lwgyBaseBed.getStudentId());
                //根据学生id查询床位信息
                List list = lwgyBaseBedMapper.selectList(queryWrapper);
                //如果有值说明已经选过床位
                if (oConvertUtils.listIsNotEmpty(list)) {
                    System.out.println("lwgyBaseBed = " + lwgyBaseBed);
                    //将床位信息放入缓存
                    redisTemplate.opsForValue().set(lwgyBaseBed.getId(), lwgyBaseBed, 3, TimeUnit.DAYS);
                    //将该学生选择的床位加入缓存，三天过期
                    redisTemplate.opsForValue().set(lwgyBaseStudent.getId(), lwgyBaseBed, 3, TimeUnit.DAYS);
                    return Result.error("已经选择过床位");
                }
            }
            //查询缓存是否有该床位
            Object lwgyBed = redisUtil.get(lwgyBaseBed.getId());
            if (oConvertUtils.isNotEmpty(lwgyBed)) {
                return Result.error("该床位已被选！");
            } else {
                queryWrapper = new QueryWrapper<>();
                queryWrapper.select("student_id");
                queryWrapper.eq("id", lwgyBaseBed.getId());
                //查询DB中该床位上是否已经有学生选择
                LwgyBaseBed lwgyBedStuID = lwgyBaseBedService.getOne(queryWrapper);
                if (oConvertUtils.isNotEmpty(lwgyBedStuID)) {
                    if (oConvertUtils.isNotEmpty(lwgyBedStuID.getStudentId())) {
                        //将床位信息放入缓存
                        redisTemplate.opsForValue().set(lwgyBaseBed.getId(), lwgyBaseBed, 3, TimeUnit.DAYS);
                        return Result.error("该床位已被选！");
                    }
                } else {
                    return Result.error("该床位不存在！");
                }
            }
            LwgyBaseBed lwgyBaseBedEntity = new LwgyBaseBed();
            lwgyBaseBedEntity.setId(lwgyBaseBed.getId());
            lwgyBaseBedEntity.setStudentId(lwgyBaseBed.getStudentId());
            //向学生选择的床位上插入学生的信息
            int i = lwgyBaseBedMapper.updateById(lwgyBaseBedEntity);
            if (i >= 1) {
                //选床位成功存历史记录
                //将该学生选择的床位加入缓存，三天过期
                redisTemplate.opsForValue().set(lwgyBaseStudent.getId(), lwgyBaseBed, 3, TimeUnit.DAYS);
                //将床位信息放入缓存
                redisTemplate.opsForValue().set(lwgyBaseBed.getId(), lwgyBaseBed, 3, TimeUnit.DAYS);
                LwgyHotelHistory lwgyHotelHistory = new LwgyHotelHistory();
                lwgyHotelHistory.setAfterBed(lwgyBaseBed.getId());
                lwgyHotelHistory.setBehavior("choose_bed");
                lwgyHotelHistory.setPersonId(lwgyBaseBed.getStudentId());
                lwgyHotelHistory.setCreateBy(lwgyBaseStudent.getStudentName());
                lwgyHotelHistoryMapper.insert(lwgyHotelHistory);
                return Result.OK("选房成功");
            }
        } finally {
            //只能释放自己的锁
            if (clientId.equals(stringRedisTemplate.opsForValue().get(lockKey))) {
                stringRedisTemplate.delete(lockKey);
            }
        }
        return Result.error("选房失败");
    }

    /**
     * 查询学生的床位
     *
     * @param studentId
     * @return
     */
    public Result getStudentBedByStudentId(String studentId) {
        List<LwgyBaseBed> lwgyBaseBeds = lwgyHotelArrangementService.getBedListByStudentId(studentId);
        return Result.OK(lwgyBaseBeds);
    }


    /**
     * 导出excel
     *
     * @param request
     * @param
     */
    @RequestMapping(value = "/outStuHotel")
    public ModelAndView outStuHotel(HttpServletRequest request, LwgyBaseBed lwgyBed) {
        List<ImportStuHotel> lwgyBaseBed = lwgyHotelArrangementService.outStuHotel(lwgyBed);
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        ImportStuHotel importStuHotel = new ImportStuHotel();
        mv.addObject(NormalExcelConstants.FILE_NAME, "住宿信息"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, ImportStuHotel.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("住宿信息", ""));
        mv.addObject(NormalExcelConstants.DATA_LIST, lwgyBaseBed);
        return mv;
    }
    /**
     * 导出excel
     *
     * @param request
     * @param
     */
    @RequestMapping(value = "/outXyScore")
    public ModelAndView outXyScore(HttpServletRequest request, LwgyBaseBed lwgyBed,@RequestParam(name = "scaleBatches") String scaleBatches) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<ImportXyScore> lwgyBaseBed = lwgyHotelArrangementService.outXyScore(lwgyBed,scaleBatches);
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        ImportStuHotel importStuHotel = new ImportStuHotel();
        mv.addObject(NormalExcelConstants.FILE_NAME, "院系打分"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, ImportXyScore.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("院系打分数据统计","导出人:"+sysUser.getRealname(), ""));
        mv.addObject(NormalExcelConstants.DATA_LIST, lwgyBaseBed);
        return mv;
    }

    /**
     * 导出住宿分配excel
     *
     * @param request
     * @param
     */
    @RequestMapping(value = "/outXyHotel")
    public ModelAndView outXyHotel(HttpServletRequest request, LwgyXyBedAssignment lwgyBed) {
        List<LwgyXyBedAssignment> lwgyBaseBed = lwgyHotelArrangementService.outXyHotel(lwgyBed);
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        LwgyXyBedAssignment lwgyBedAssignment = new LwgyXyBedAssignment();
        mv.addObject(NormalExcelConstants.FILE_NAME, "住宿分配信息"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, LwgyXyBedAssignment.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("住宿分配信息", ""));
        mv.addObject(NormalExcelConstants.DATA_LIST, lwgyBaseBed);
        return mv;
    }
    /**
     * 导出辅导员打分excel
     *
     * @param request
     * @param
     */
   /* @RequestMapping(value = "/outTeacherScore")
    public ModelAndView outTeacherScore(HttpServletRequest request, LwgyBaseBed lwgyBed,@RequestParam(name = "scaleBatches") String scaleBatches) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> role = lwgyBaseBedService.getRoleById(sysUser.getId());
        //不是管理员，显示管理员分配的的床位
        if (role.contains("fdy")) {
            String workNo = sysUser.getWorkNo();
            lwgyBed.setAdminId(workNo);
        }
        List<ImportTeacherScore> lwgyBaseBed = lwgyHotelArrangementService.outTeacherScore(lwgyBed,scaleBatches);
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        ImportStuHotel importStuHotel = new ImportStuHotel();
        mv.addObject(NormalExcelConstants.FILE_NAME, "辅导员打分"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, ImportTeacherScore.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("辅导员打分数据统计","导出人:"+sysUser.getRealname(), ""));
        mv.addObject(NormalExcelConstants.DATA_LIST, lwgyBaseBed);
        return mv;
    }*/
    @RequestMapping(value = "/outTeacherScore")
    public void outTeacherScore(HttpServletRequest request, HttpServletResponse response, LwgyBaseBed lwgyBed) throws IOException{
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> role = lwgyBaseBedService.getRoleById(sysUser.getId());
        //不是管理员，显示管理员分配的的床位
        if (role.contains("fdy")) {
            String workNo = sysUser.getWorkNo();
            lwgyBed.setAdminId(workNo);
        }

        List<ImportTeacherScore> lwgyBaseTacherScore1 = lwgyHotelArrangementService.outTeacherScore1(lwgyBed);

        // 获取上半年和下半年的最大周数
        int maxUpperWeek = getMaxWeekFromBatchName(lwgyBaseTacherScore1, "上半年");
        int maxLowerWeek = getMaxWeekFromBatchName(lwgyBaseTacherScore1, "下半年");
        LinkedHashMap<String, List<ImportTeacherScore>> lwgyBaseTeacher = lwgyBaseTacherScore1.stream()
                .collect(Collectors.groupingBy(ImportTeacherScore::getRoomId, LinkedHashMap::new, Collectors.toList()));

        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();


        lwgyBaseTeacher.forEach((key, value) -> {
            // 在循环中创建新的 map1 对象
            Map<String, Object> map1 = new HashMap<>();

            // 存储每个房间的ABCD数量
            Map<String, Integer> roomACountMap = new HashMap<>();
            Map<String, Integer> roomBCountMap = new HashMap<>();
            Map<String, Integer> roomCCountMap = new HashMap<>();
            Map<String, Integer> roomDCountMap = new HashMap<>();

            // 存储每个房间的总成绩和房间数量

            Map<String, Double> roomTotalScoreMap = new HashMap<>();
            Map<String, Integer> roomCountMap = new HashMap<>();
            // 房间
            List<ImportTeacherScore> list = value;
            list.forEach(p -> {
                String roomName = p.getRoomName();

                map1.put("roomNames", p.getRoomNames());
                map1.put("roomName", p.getRoomName());
                map1.put("studentTeacher", p.getStudentTeacher());
                map1.put("remark", p.getRemark());

                // 从batchName中获取上半年和下半年信息
                String batchName = p.getBatchName();
                if (batchName.contains("上半年")) {
                    if (p.getTotalScore() != null) {
                        // 生成对应的第几周，传递上半年的最大周数和下半年的最大周数
                        int week = generateWeekFromBatchName(batchName, maxUpperWeek, maxLowerWeek, true);
                        map1.put(week + "link_totalScore", p.getTotalScore());
                        map1.put(week + "link_totalScores", p.getTotalScores());
                    }
                } else if (batchName.contains("下半年")) {
                    int week = generateWeekFromBatchName(batchName, maxUpperWeek, maxLowerWeek, false);
                    map1.put(week + "link_totalScoreBee", p.getTotalScoreBee());
                    map1.put(week + "link_totalScoresBee", p.getTotalScoresBee());
                }

                String totalScoreStr = p.getTotalScoresBee();
                double totalScore = Double.parseDouble(totalScoreStr);
                // 更新房间的总成绩和房间数量
                roomTotalScoreMap.put(roomName, roomTotalScoreMap.getOrDefault(roomName, 0.0) +totalScore);
                roomCountMap.put(roomName, roomCountMap.getOrDefault(roomName, 0) + 1);
                // 统计每个房间的A数量
                int aCount = p.getACount();
                int bCount = p.getBCount();
                int cCount = p.getCCount();
                int dCount = p.getDCount();
                roomACountMap.put(roomName, roomACountMap.getOrDefault(roomName, 0) + aCount);
                roomBCountMap.put(roomName, roomBCountMap.getOrDefault(roomName, 0) + bCount);
                roomCCountMap.put(roomName, roomCCountMap.getOrDefault(roomName, 0) + cCount);
                roomDCountMap.put(roomName, roomDCountMap.getOrDefault(roomName, 0) + dCount);
            });
            // 计算平均成绩
            Map<String, String> roomAverageScoreMap = new HashMap<>();
            roomTotalScoreMap.forEach((roomName, totalScore) -> {
                int roomCount = roomCountMap.getOrDefault(roomName, 0);
                double averageScore = roomCount > 0 ? (double) totalScore / roomCount : 0.0;
                String averageScoreStr = String.format("%.2f", averageScore);
                roomAverageScoreMap.put(roomName, averageScoreStr);
            });


            // 将房间的A数量添加到map1中
            roomACountMap.forEach((roomName, aCount) -> {
                map1.put("ACount", aCount);
            });
            // 将房间的B、C、D数量添加到map1中
            roomBCountMap.forEach((roomName, bCount) -> {
                map1.put("BCount", bCount);
            });
            roomCCountMap.forEach((roomName, cCount) -> {
                map1.put("CCount", cCount);
            });
            roomDCountMap.forEach((roomName, dCount) -> {
                map1.put("DCount", dCount);
            });


            // 将每个房间的平均成绩乘以10并添加到map1中
            roomAverageScoreMap.forEach((roomName, averageScore) -> {
                double scaledAverageScore = Double.parseDouble(averageScore) * 10;
                String scaledAverageScoreStr = String.format("%.2f", scaledAverageScore);
                map1.put("pjcj", scaledAverageScoreStr);
            });

            dataList.add(map1);

        });

        List<ExcelExportEntity> entityList = ExcelImports.ExcelImportUtil(maxUpperWeek, maxLowerWeek);
        Workbook wb = ExcelExportUtil.exportExcel(new ExportParams(null, "sheetName"), entityList, dataList);
        try {
            String fileName = "用户信息表";
            OutputStream output = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"), "utf-8") + ".xls");
            wb.write(output);
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }






    private int generateWeekFromBatchName(String batchName, int maxUpperWeek, int maxLowerWeek, boolean isUpperHalfYear) {
        Matcher matcher = Pattern.compile("第(\\d+)").matcher(batchName);
        int week = matcher.find() ? Integer.parseInt(matcher.group(1)) : 0;

        int maxWeekForBatch = isUpperHalfYear ? maxUpperWeek : maxLowerWeek;

        // 根据半年类型和最大周数进行限制
        if (week > maxWeekForBatch) {
            week = maxWeekForBatch;
        } else if (week <= 0) {
            week = 1;
        }

        return week;
    }
    private int getMaxWeekFromBatchName(List<ImportTeacherScore> scores, String batchType) {
        int maxWeek = 0;

        for (ImportTeacherScore score : scores) {
            String batchName = score.getBatchName();
            if (batchName != null && batchName.contains(batchType)) {
                String weeks = score.getWeeks();
                if (weeks != null && !weeks.isEmpty()) {
                    String[] weekArray = weeks.split(",");
                    for (String week : weekArray) {
                        int currentWeek = Integer.parseInt(week.trim());
                        if (currentWeek > maxWeek) {
                            maxWeek = currentWeek;
                        }
                    }
                }
            }
        }

        return maxWeek;
    }

   /*private int generateWeekFromBatchName(String batchName, int maxUpperWeek, int maxLowerWeek, boolean isUpperHalfYear) {
       int week = 0;

       // 从 batchName 中提取周数信息
       String[] parts = batchName.split("第");
       if (parts.length > 1) {
           String weekInfo = parts[1];
           week = Integer.parseInt(weekInfo.replaceAll("[^0-9]", ""));
       }

       // 根据批次类型的不同，分别使用对应的最大周数进行比较和限制
       int maxWeekForBatch = isUpperHalfYear ? maxUpperWeek : maxLowerWeek;
       if (week > maxWeekForBatch) {
           week = maxWeekForBatch;
       } else if (week <= 0) {
           week = 1;
       }

       return week;
   }*/


    /**
     * 导出excel
     *
     * @param request
     * @param
     */
    @RequestMapping(value = "/outScore")
    public ModelAndView outScore(HttpServletRequest request, LwgyBaseBed lwgyBed,@RequestParam(name = "scaleBatches") String scaleBatches) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        List<String> role = lwgyBaseBedService.getRoleById(sysUser.getId());
        //不是管理员，显示管理员分配的的床位
        if (role.contains("fdy")) {
            String workNo = sysUser.getWorkNo();
            lwgyBed.setAdminId(workNo);
        }
        List<ImportScore> lwgyBaseBed = lwgyHotelArrangementService.outScore(lwgyBed,scaleBatches);
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        ImportStuHotel importStuHotel = new ImportStuHotel();
        //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, "卫生打分");
        mv.addObject(NormalExcelConstants.CLASS, ImportScore.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("卫生打分数据","导出人:"+sysUser.getRealname(), ""));
        mv.addObject(NormalExcelConstants.DATA_LIST, lwgyBaseBed);
        return mv;
    }

    /**
     * 导出excel模板
     *
     * @param request
     * @param
     */
    @RequestMapping(value = "/outStuTemplate")
    public ModelAndView outStuTemplate(HttpServletRequest request, LwgyBaseBed lwgyBed) {
        List<ImportStuHotelBed> lwgyBaseBed = new ArrayList<>(1);
        ImportStuHotelBed importStuHotel = new ImportStuHotelBed();
        importStuHotel.setBuildingName("GA1(必填)");
        importStuHotel.setRoomName("101(必填)");
        importStuHotel.setBedName("01(必填)");
        importStuHotel.setStudentName("姓名(必填)");
        importStuHotel.setStudentNumber("202182080040(必填)");
        lwgyBaseBed.add(importStuHotel);
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, "住宿信息");
        mv.addObject(NormalExcelConstants.CLASS, ImportStuHotelBed.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("住宿信息", ""));
        mv.addObject(NormalExcelConstants.DATA_LIST, lwgyBaseBed);
        return mv;
    }


    @ApiOperation(value = "床位批量绑定辅导员", notes = "床位批量绑定辅导员")
    @PutMapping("/bedBatchBindTeacher")
    public Result bedBatchBindTeacher(String bedIds, String teacherIds, String facultyId) {
        if (oConvertUtils.isEmpty(bedIds)) {
            return Result.error("请先选择床位!");
        }
        String[] bedId = bedIds.split(",");
        try {
            lwgyHotelArrangementService.bedBatchBindTeacher(Arrays.asList(bedId), teacherIds, facultyId);
        } catch (Exception e) {
            return Result.error("未知的错误,绑定失败!");
        }
        return Result.OK("绑定成功", null);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param
     */
    @RequestMapping(value = "/StuZsHotel")
    public void StuZsHotel(HttpServletRequest request, HttpServletResponse response, LwgyBaseBed lwgyBed) throws IOException {
        System.out.println("导出+++++++");
        //获取所有床位信息。
        List<StuHotelRoster> lwgyBaseBed = lwgyHotelArrangementService.StuZsHotel(lwgyBed);
        System.out.println( " lwgyBaseBedddd"+lwgyBaseBed);
        //获取最大床位数
        IntSummaryStatistics resultNum = lwgyBaseBed.stream().mapToInt((item) -> Integer.parseInt(item.getBedName())).summaryStatistics();
        Integer info = resultNum.getMax();
        //楼宇名字修改为楼名_房间名
//        lwgyBaseBed.stream().forEach(r -> r.setBuildingName(r.getBuildingName() + "-" + r.getRoomName()));
        //专业班级修改为专业名_班级名
        lwgyBaseBed.stream().forEach(r -> r.setMajorName(r.getMajorName() + "-" + r.getClassName()));
        //获取每个房间的信息。
        LinkedHashMap<String, List<StuHotelRoster>> lwgyBaseBedT = lwgyBaseBed.stream()
                .collect(Collectors.groupingBy(StuHotelRoster::getRoomId,LinkedHashMap::new, Collectors.toList()));

        System.out.print("=========================== //获取房间信息" + lwgyBaseBedT);
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();

        //按照房间信息循环
        lwgyBaseBedT.forEach((key, value) -> {
            AtomicReference<Double> a = new AtomicReference<>(0.0);
            AtomicReference<Double> b = new AtomicReference<>(0.0);
            Map<String, Object> map1 = new HashMap<>();
            //房间
            List<StuHotelRoster> list = value;
            list.stream().forEach(p -> {
                map1.put("campusName", p.getCampusName());
                map1.put("buildingName", p.getBuildingName());
                map1.put("roomName", p.getRoomName());

                for (int i = 1; i <= info; i++) {
                    if (p.getBedName().contains(i + "")) {
                        map1.put(i + "link_num", p.getStudentNumber());
                        map1.put(i + "link_name", p.getStudentName());
                        if(oConvertUtils.isEmpty(p.getClassName())){
                            map1.put(i + "majorClass", null);
                        } else {
                            map1.put(i + "majorClass", p.getMajorName());
                        }
                        map1.put(i + "beforeInfo", p.getBeforeInfo());

//                        if (ObjectUtils.isNotEmpty(p.getStateCharge())){
//                            a.updateAndGet(v -> new Double((double) (v + Double.parseDouble(p.getStateCharge()))));
//                        }
//                        if (ObjectUtils.isNotEmpty(p.getStateFreeCharge())){
//                            b.updateAndGet(v -> new Double((double) (v + Double.parseDouble(p.getStateFreeCharge()))));
//                        }
                    }
                }
//                map1.put("stateCharge",a);
//                map1.put("stateFreeCharge",b);
            });
            dataList.add(map1);
        });
        //获取最大床位数
        int bedsize = info;
        List<ExcelExportEntity> entityList = ExcelImport.ExcelImportUtil(bedsize);
        Workbook wb = ExcelExportUtil.exportExcel(new ExportParams(null, "sheetName"), entityList, dataList);
        try {
            String fileName = "用户信息表";
            OutputStream output = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"), "utf-8") + ".xls");
            wb.write(output);
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过excel导入数据进行退宿。表格中只有两种信息，学号，姓名
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcelUrlToTs", method = RequestMethod.POST)
    public Result<?> importExcelUrlToTs(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        MultipartFile file = fileMap.get("file");
        try {
            ImportParams params = new ImportParams();
            params.setNeedSave(true);
            params.setTitleRows(1);// 设置第一行为标题
            params.setHeadRows(2);// 设置第一行为标题
            List<ImportLwgyStu> list = ExcelImportUtil.importExcel(file.getInputStream(), ImportLwgyStu.class, params);
            List<String> numbers = new ArrayList<>(list.size());
            list.stream().forEach(item -> {
                numbers.add(item.getStuNumber());
            });

            List<LwgyHotelArrangement> listT = lwgyHotelArrangementService.queryStuBedByNumberList(numbers);
            if (oConvertUtils.isNotEmpty(listT) && listT.size() > 0) {
                String ids = "";
                LwgyHotelHistory lwgyHotelHistory;
                List<LwgyHotelHistory> arrangementList = new ArrayList<>();
                LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                for (LwgyHotelArrangement stu : listT) {
                    ids += stu.getBeforeBed() + ",";
                    lwgyHotelHistory = JSON.parseObject(JSON.toJSONString(stu), LwgyHotelHistory.class);

                    lwgyHotelHistory.setPersonId(stu.getStudentId());
                    lwgyHotelHistory.setCreateBy(sysUser.getUsername());
                    arrangementList.add(lwgyHotelHistory);
                }
                lwgyHotelArrangementService.cleanBed(ids);//批量清空住宿
                lwgyHotelHistoryService.saveBatch(arrangementList);//批量存储退宿记录
            }


            return Result.OK("成功退宿" + listT.size() + "名学生");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.OK();

    }

    /**
     * 通过excel导入
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        MultipartFile file = fileMap.get("file");
        try {
            long start = System.currentTimeMillis();
            ImportParams params = new ImportParams();
            params.setNeedSave(true);
            params.setTitleRows(1);//设置第一行为标题
            params.setHeadRows(2);//第二行为表头
            List<ImportStuHotelBed> list = ExcelImportUtil.importExcel(file.getInputStream(), ImportStuHotelBed.class, params);
            List<ImportStuHotelBed> errList1 = new ArrayList<>();
            List<ImportStuHotelBed> errList2 = new ArrayList<>();
            List<ImportStuHotelBed> errList3 = new ArrayList<>();
            List<ImportStuHotelBed> errList4 = new ArrayList<>();
            List<LwgyHotelHistory> arrangementList = new ArrayList<>();
            List<LwgyBaseBed> bedList = new ArrayList<>();
            LwgyBaseBed lwgyBaseBed;
            LwgyHotelHistory lwgyHotelHistory;

            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String username = sysUser.getUsername();
            List<String> roles = sysBaseAPI.getRolesByUsername(username);


            //通过导入的学生的姓名，学号，查询学生的id和班级
            list = lwgyHotelArrangementService.selectStudentIdList(list);
            //辅导员只能导入自己学院的学生，排查后将错误数据写入errList表中
            if(roles.contains("fdy")){
                List<String> classId = lwgyBaseStudentService.getClassIdBySysUser(sysUser);
                if (oConvertUtils.listIsNotEmpty((classId))) {

                    errList3 = list.stream().filter(item->oConvertUtils.isNotEmpty(item.getStudentClass()) && !(classId.contains(item.getStudentClass()))).collect(Collectors.toList());
                    list= list.stream().filter(item->oConvertUtils.isNotEmpty(item.getStudentClass()) || classId.contains(item.getStudentClass()) ).collect(Collectors.toList());

                    if(errList3.size()>0){
                        errList3.stream().forEach(item->{
                            item.setReason("非本学院学生无法安排");
                        });
                    }
                }
                errList4 = list.stream().filter(item->!((username).equals(item.getAdminId()))).collect(Collectors.toList());
                list= list.stream().filter(item->(username).equals(item.getAdminId())).collect(Collectors.toList());
                if(errList4.size()>0){
                    errList4.stream().forEach(item->{
                        item.setReason("非本学院床位无法安排");
                    });
                }

            }
            //id为空的数据判断为学生不存在，写入errlist表中
            errList1 = list.stream().filter(item->oConvertUtils.isEmpty(item.getStudentId())&&oConvertUtils.isNotEmpty(item.getStudentNumber())).collect(Collectors.toList());
            if(errList1.size()>0){
             errList1.stream().forEach(item->{
                 item.setReason("学生不存在");
             });
            }
            list= list.stream().filter(item->oConvertUtils.isNotEmpty(item.getStudentId())||oConvertUtils.isEmpty(item.getStudentNumber())).collect(Collectors.toList());

            errList2 = list.stream().filter(item->oConvertUtils.isEmpty(item.getBedId())).collect(Collectors.toList());
            if(errList2.size()>0){
                errList2.stream().forEach(item->{
                    item.setReason("床位不存在");
                });
            }
            errList1.addAll(errList2);
            errList1.addAll(errList3);
            errList1.addAll(errList4);

            list= list.stream().filter(item->oConvertUtils.isNotEmpty(item.getBedId())).collect(Collectors.toList());




            Map<String, List<ImportStuHotelBed>> collect1 = list.stream()
                    .filter(item-> StringUtils.isNotBlank(item.getStudentNumber())).collect
                            (Collectors.groupingBy(ImportStuHotelBed::getStudentNumber));
            Map<String, List<ImportStuHotelBed>> collect2 = list.stream()
                    .filter(item-> StringUtils.isNotBlank(item.getBedId())).collect
                            (Collectors.groupingBy(ImportStuHotelBed::getBedId));
            Iterator<ImportStuHotelBed> iterator=list.iterator();
            while (iterator.hasNext()){
                ImportStuHotelBed importStuHotel = iterator.next();
                if(collect1.containsKey(importStuHotel.getStudentNumber())){
                    String a = importStuHotel.getStudentNumber();
                    if(collect1.get(a).size()>1){
                        importStuHotel.setReason("学号重复");
                        errList1.add(importStuHotel);
                        iterator.remove();
                        continue;
                    }
                }
                if(collect2.containsKey(importStuHotel.getBedId())){
                    if(collect2.get(importStuHotel.getBedId()).size()>1) {
                        importStuHotel.setReason("床位重复");
                        errList1.add(importStuHotel);
                        iterator.remove();
                        continue;
                    }
                }
            }


        //获取导入床位的当前住宿情况（导入的床位上原先是否存在学生）
            List<ImportStuHotelBed> listBed = lwgyHotelArrangementService.selectBedByStuList(list);


            if (list.size() > 0) {
                String tsIds = "";
                String tsStuIds = "";
                String insertStuIds = "";
                for (ImportStuHotelBed item : list) {
                    for (ImportStuHotelBed item2 : listBed) {
                      /*  if (item.getCampusName().equals(item2.getCampusName())
                                && item.getBuildingName().equals(item2.getBuildingName())
                                && item.getUnitName().equals(item2.getUnitName())
                                && item.getRoomName().equals(item2.getRoomName())
                                && item.getBedName().equals(item2.getBedName())) {*/
                        if (item.getBedId().equals(item2.getBedId())) {


                            lwgyBaseBed = new LwgyBaseBed();
                            lwgyHotelHistory = new LwgyHotelHistory();
                            if (oConvertUtils.isNotEmpty(item2.getStudentId())
                                    && oConvertUtils.isEmpty(item.getStudentId())) {
                                tsIds += item2.getBedId() + ",";
                                tsStuIds += item2.getStudentId() + ",";
                                System.out.print("退宿---------------------------" + item2.getBedId());
                            }
                            String stuIds = item.getStudentId();
                            LwgyHotelRequisition lwgyHotel = lwgyHotelRequisitionService.getStuAdmin(stuIds);
                            //系统非空，表非空，但是系统中用户与表中不一致--退+住
                            if (oConvertUtils.isNotEmpty(item2.getStudentId())
                                    && oConvertUtils.isNotEmpty(item.getStudentId())
                                    && !item.getStudentId().equals(item2.getStudentId())) {
                                tsIds += item2.getBedId() + ",";
                                tsStuIds += item2.getStudentId() + ",";
                                insertStuIds += item.getStudentId() + ",";
                                lwgyBaseBed.setId(item2.getBedId());
                                lwgyBaseBed.setStudentId(item.getStudentId());
                                lwgyBaseBed.setAdminId(lwgyHotel.getAdminName());
                                bedList.add(lwgyBaseBed);
                                lwgyHotelHistory.setBehavior("choose_bed");
                                lwgyHotelHistory.setPersonId(item.getStudentId());
                                lwgyHotelHistory.setAfterBed(item2.getBedId());
                                arrangementList.add(lwgyHotelHistory);


                            }
                            //系统空，表非空，住
                            if (oConvertUtils.isEmpty(item2.getStudentId())
                                    && oConvertUtils.isNotEmpty(item.getStudentId())) {

                                insertStuIds += item.getStudentId() + ",";
                                lwgyBaseBed.setId(item2.getBedId());
                                lwgyBaseBed.setStudentId(item.getStudentId());
                                lwgyBaseBed.setAdminId(lwgyHotel.getAdminName());
                                lwgyBaseBed.setUpdateTime(new Date());
                                bedList.add(lwgyBaseBed);

                                lwgyHotelHistory.setBehavior("choose_bed");
                                lwgyHotelHistory.setPersonId(item.getStudentId());
                                lwgyHotelHistory.setAfterBed(item2.getBedId());
                                arrangementList.add(lwgyHotelHistory);
                            }


                        }
                    }
                }

                //要安排住宿的学生之前是否有住宿信息
                if(insertStuIds.length()>0){
                    List<LwgyBaseBed> bedListByStu = lwgyHotelArrangementService.selectStuBedByStuId(insertStuIds);
                    if (oConvertUtils.isNotEmpty(bedListByStu)) {
                        for (LwgyBaseBed item : bedListByStu) {
                            tsIds += item.getId() + ",";
                            tsStuIds += item.getStudentId() + ",";
                        }
                    }
                }
                System.out.print("退宿---------------------------" + tsIds);
                if (tsIds.length() > 0) {
                    List<LwgyHotelHistory> arrangementList2 = lwgyHotelArrangementService.leaveBedHistory(tsStuIds);
                    lwgyHotelArrangementService.cleanBed(tsIds);//批量清空住宿
                    lwgyHotelHistoryService.saveBatch(arrangementList2);//批量存储退宿记录
                }
                if (bedList.size() > 0) {
                    lwgyBaseBedService.updateBatchById(bedList);//更新入住信息
                    lwgyHotelHistoryService.saveBatch(arrangementList);//保存历史记录
                }
            }
            long end = System.currentTimeMillis();

            if (errList1.size() == 0) {
                Map paramsMsg = new HashMap();
                paramsMsg.put("message", "成功导入" + list.size() + "条数据,共耗时:" + (end - start) / 1000 + "秒");
                return Result.OK(paramsMsg);
            } else {
                Map paramsMsg = new HashMap();
                paramsMsg.put("message", "成功导入" + list.size() + "条数据，共耗时:" + (end - start) / 1000 + "秒，存在" + errList1.size() + "条问题数据，是否导出？");
                paramsMsg.put("data", errList1);
                return Result.OK(paramsMsg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.OK();
    }

    /**
     * 通过excel导入(发现没上一个方法执行快)
     *
     * @param request
     * @param response
     * @return
     */
    /*@RequestMapping(value = "/importExcel1", method = RequestMethod.POST)
    public Result<?> importExcel1(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        MultipartFile file = fileMap.get("file");
        try {
            long start = System.currentTimeMillis();
            ImportParams params = new ImportParams();
            params.setNeedSave(true);
            params.setTitleRows(1);//设置第一行为标题
            params.setHeadRows(2);//第二行为表头
            List<ImportStuHotel> list = ExcelImportUtil.importExcel(file.getInputStream(), ImportStuHotel.class, params);
            List<ImportStuHotel> errList1 = new ArrayList<>();
            String stuIds = "";
            String bedIds = "";
            String tsIds = "";
            String tsStuIds="";
            List<LwgyHotelHistory> arrangementList = new ArrayList<>();
            List<LwgyBaseBed> bedList = new ArrayList<>();


            //通过导入的学生的姓名，学号，查询学生的id 及床位id
            list = lwgyHotelArrangementService.selectStudentIdList(list);

            Map<String, List<ImportStuHotel>> collect1 = list.stream()
                    .filter(item-> StringUtils.isNotBlank(item.getStudentNumber())).collect
                            (Collectors.groupingBy(ImportStuHotel::getStudentNumber));
            Map<String, List<ImportStuHotel>> collect2 = list.stream()
                    .filter(item-> StringUtils.isNotBlank(item.getBedId())).collect
                            (Collectors.groupingBy(ImportStuHotel::getBedId));
            //id为空的数据判断为学生不存在，写入errlist表中

            Iterator<ImportStuHotel> iterator=list.iterator();
            while (iterator.hasNext()){
                ImportStuHotel importStuHotel = iterator.next();
                if(oConvertUtils.isEmpty(importStuHotel.getStudentId())&&oConvertUtils.isNotEmpty(importStuHotel.getStudentNumber())){
                    importStuHotel.setReason("学生不存在");
                    errList1.add(importStuHotel);
                    iterator.remove();
                    continue;
                }
                if(oConvertUtils.isEmpty(importStuHotel.getBedId())){
                    importStuHotel.setReason("床位不存在");
                    errList1.add(importStuHotel);
                    iterator.remove();
                    continue;
                }
                if(collect1.containsKey(importStuHotel.getStudentNumber())){
                    String a = importStuHotel.getStudentNumber();
                    if(collect1.get(a).size()>1){
                        importStuHotel.setReason("学号重复");
                        errList1.add(importStuHotel);
                        iterator.remove();
                        continue;
                    }
                }
                if(collect2.containsKey(importStuHotel.getBedId())){
                    if(collect2.get(importStuHotel.getBedId()).size()>1) {
                        importStuHotel.setReason("床位重复");
                        errList1.add(importStuHotel);
                        iterator.remove();
                        continue;
                    }
                }
                //获取所有没问题的学生ids和bedIds
                if(oConvertUtils.isNotEmpty(importStuHotel.getStudentId())){
                    stuIds+=importStuHotel.getStudentId()+",";
                }
                if(oConvertUtils.isNotEmpty(importStuHotel.getBedId())){
                    bedIds+=importStuHotel.getBedId()+",";
                }
            }



            //床位，及学生之前的住宿情况
            List<LwgyBaseBed> bedListByStu = lwgyHotelArrangementService.selectStuBedById(stuIds,bedIds);

            if (list.size() > 0) {
                for (LwgyBaseBed item : bedListByStu) {
                    tsIds += item.getId() + ",";
                    tsStuIds += item.getStudentId() + ",";
                }

                for (ImportStuHotel item : list) {
                    LwgyBaseBed lwgyBaseBed = new LwgyBaseBed();
                    lwgyBaseBed.setId(item.getBedId());
                    lwgyBaseBed.setStudentId(item.getStudentId());
                    bedList.add(lwgyBaseBed);
                }
                //要安排住宿的学生之前是否有住宿信息
                if (tsIds.length() > 0) {
                    List<LwgyHotelHistory> arrangementList2 = lwgyHotelArrangementService.leaveBedHistory(tsStuIds);
                    lwgyHotelArrangementService.cleanBed(tsIds);//批量清空住宿
                    lwgyHotelHistoryService.saveBatch(arrangementList2);//批量存储退宿记录
                }
                if (bedList.size() > 0) {
                    lwgyBaseBedService.updateBatchById(bedList);//更新入住信息
                    lwgyHotelHistoryService.saveBatch(arrangementList);//保存历史记录
                }


                long end = System.currentTimeMillis();

                if (errList1.size() == 0) {
                    Map paramsMsg = new HashMap();
                    paramsMsg.put("message", "成功导入" + list.size() + "条数据,共耗时:" + (end - start) / 1000 + "秒");
                    return Result.OK(paramsMsg);
                } else {
                    Map paramsMsg = new HashMap();
                    paramsMsg.put("message", "成功导入" + list.size() + "条数据，共耗时:" + (end - start) / 1000 + "秒，存在" + errList1.size() + "条问题数据，是否导出？");
                    paramsMsg.put("data", errList1);
                    return Result.OK(paramsMsg);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.OK();
    }*/

    /**
     * 通过excel导入数据进行离校。表格中只有两种信息，学号，姓名
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcelUrlToLx", method = RequestMethod.POST)
    public Result<?> importExcelUrlToLx(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        MultipartFile file = fileMap.get("file");
        try {
            ImportParams params = new ImportParams();
            params.setNeedSave(true);
            // 设置第一行为标题
            params.setTitleRows(1);
            // 设置第一行为标题
            params.setHeadRows(2);
            List<ImportStuHotel> list = ExcelImportUtil.importExcel(file.getInputStream(), ImportStuHotel.class, params);
            List<ImportStuHotel> errList1 = new ArrayList<>();
            List<ImportStuHotel> errList2 = new ArrayList<>();
            List<String> numbers = new ArrayList<>(list.size());
            list.stream().forEach(item -> {
                numbers.add(item.getStudentNumber());
            });
            //通过导入的学生的姓名，学号，查询学生的id和班级
            list = lwgyHotelArrangementService.selectStudentIdListX(list);
            List<LwgyHotelArrangement> listT = lwgyHotelArrangementService.queryStuBedByNumberList(numbers);
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String username = sysUser.getUsername();
            List<String> roles = sysBaseAPI.getRolesByUsername(username);
            if(roles.contains("fdy")) {
                List<String> classId = lwgyBaseStudentService.getClassIdBySysUser(sysUser);
                if (oConvertUtils.isNotEmpty(classId)) {
                    errList1 = list.stream().filter(item->oConvertUtils.isNotEmpty(item.getStudentClass()) && !(classId.contains(item.getStudentClass()))).collect(Collectors.toList());
                    list = list.stream().filter(item->oConvertUtils.isNotEmpty(item.getStudentClass()) || classId.contains(item.getStudentClass()) ).collect(Collectors.toList());

                    if(errList1.size()>0){
                        errList1.stream().forEach(item->{
                            item.setReason("非本学院学生无法离校");
                        });
                    }
                }
            }
            if (oConvertUtils.isNotEmpty(list) && list.size() > 0) {
                String stuIds = "";
                for (ImportStuHotel stu : list) {
                    stuIds += stu.getStudentId() + ",";
                }
                //批量离校
                lwgyHotelArrangementService.leaveSchool(stuIds);
            }
            if (oConvertUtils.isNotEmpty(listT) && listT.size() > 0) {
                String ids = "";
                LwgyHotelHistory lwgyHotelHistory;
                List<LwgyHotelHistory> arrangementList = new ArrayList<>();
                for (LwgyHotelArrangement stuBed : listT) {
                    ids += stuBed.getBeforeBed() + ",";
                    lwgyHotelHistory = JSON.parseObject(JSON.toJSONString(stuBed), LwgyHotelHistory.class);
                    lwgyHotelHistory.setPersonId(stuBed.getStudentId());
                    lwgyHotelHistory.setBehavior(stuBed.getBehavior());
                    lwgyHotelHistory.setBeforeBed(stuBed.getBeforeBed());
                    lwgyHotelHistory.setAfterBed(stuBed.getAfterBed());
                    lwgyHotelHistory.setCreateBy(sysUser.getUsername());
                    arrangementList.add(lwgyHotelHistory);
                }

                lwgyHotelArrangementService.cleanBed(ids);//批量清空住宿
                lwgyHotelHistoryService.saveBatch(arrangementList);//批量存储退宿记录
            }
            if (errList1.size() == 0) {
                return Result.OK("成功离校" + listT.size() + "名学生");
            } else {
                return Result.OK("成功离校" + listT.size() + "名学生"+ "，存在" +errList1.size() + "条问题数据");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.OK();
    }
    /**
     * 自动安排入住
     *
     * @param autoAssign
     * @return
     */
    @AutoLog(value = "自动安排入住")
    @ApiOperation(value = "自动安排入住", notes = "自动安排入住")
    @PostMapping(value = "/bedAssignment")
    public Result<?> bedAssignment(@RequestBody AutoAssignBed autoAssign) {
        System.out.println("autoAssign = " + autoAssign);

        //查询在校但是没有住宿的学生
        QueryWrapper<AutoAssignStu> queryWrapperStu = new QueryWrapper<>();
        //查询有学生但是没有管理员的所有床位
        QueryWrapper<AutoAssignBed> queryWrapperBed = new QueryWrapper<>();

        if(StringUtils.isNotBlank(autoAssign.getStudentCampus())) {
            queryWrapperStu.eq("ls.student_campus", autoAssign.getStudentCampus());
        }
        if(StringUtils.isNotBlank(autoAssign.getStudentCollege())) {
            queryWrapperStu.eq("ls.student_college", autoAssign.getStudentCollege());
        }
        if(StringUtils.isNotBlank(autoAssign.getStudentYear())) {
            queryWrapperStu.eq("ls.student_year", autoAssign.getStudentYear());
        }
        if(StringUtils.isNotBlank(autoAssign.getStudentMajor())) {
            queryWrapperStu.eq("ls.student_major", autoAssign.getStudentMajor());
        }
        if(StringUtils.isNotBlank(autoAssign.getStudentClass())) {
            queryWrapperStu.eq("ls.student_class", autoAssign.getStudentClass());
        }
        if(StringUtils.isNotBlank(autoAssign.getStudentEducation())) {
            queryWrapperStu.eq("ls.student_education", autoAssign.getStudentEducation());
        }
        queryWrapperStu.eq("ls.student_state",0);
        queryWrapperStu.isNull("b.student_id");
        List<AutoAssignStu> stuList = autoAssignService.getStuBed(queryWrapperStu);

        if(StringUtils.isNotBlank(autoAssign.getSchoolId())) {
            queryWrapperBed.eq("campus_id", autoAssign.getSchoolId());
        }
        if(StringUtils.isNotBlank(autoAssign.getBuildingId())) {
            queryWrapperBed.eq("building_id", autoAssign.getBuildingId());
        }
        if(StringUtils.isNotBlank(autoAssign.getUnitId())) {
            queryWrapperBed.eq("unit_id", autoAssign.getUnitId());
        }
        queryWrapperBed.and(queryWrapper -> queryWrapper.isNull("lb.student_id").or().eq("lb.student_id",""));
        queryWrapperBed.orderByDesc("lb.id");
        List<AutoAssignBed> bedList = autoAssignService.getTeaCol(queryWrapperBed);

        List<LwgyBaseBed> baseBedList = new ArrayList<>();
        List<LwgyHotelHistory> arrangementList = new ArrayList<>();

        stuList.stream().forEach(item1 -> {
            bedList.stream().filter(item2 -> item1.getUserName().equals(item2.getAdminId())
                    && item1.getStudentSex().equals(item2.getRoomSex())
                    && oConvertUtils.isEmpty(item2.getStudentId())
            ).limit(1).map(autobed->autobed.setStudentId(item1.getStudentId())).forEach(item->{
                LwgyBaseBed lwgyBaseBed = new LwgyBaseBed();
                LwgyHotelHistory lwgyHotelHistory = new LwgyHotelHistory();
                lwgyBaseBed.setId(item.getId());
                lwgyBaseBed.setStudentId(item1.getStudentId());
                lwgyBaseBed.setUpdateTime(new Date());
                baseBedList.add(lwgyBaseBed);

                lwgyHotelHistory.setBehavior("choose_bed");
                lwgyHotelHistory.setAfterBed(item.getId());
                lwgyHotelHistory.setPersonId(item1.getStudentId());
                arrangementList.add(lwgyHotelHistory);
            });
        });
        // 更新住宿信息
        lwgyBaseBedService.updateBatchById(baseBedList);
        // 保存历史纪录
        lwgyHotelHistoryService.saveBatch(arrangementList);
        return Result.OK("操作成功!");
    }

    /**
     * 自动分配床位
     *
     * @param autoAssign
     * @return
     */
    @AutoLog(value = "自动分配床位")
    @ApiOperation(value = "自动分配床位", notes = "自动分配床位")
    @PostMapping(value = "/assigningBed")
    public Result<?> assigningBed(@RequestBody AutoAssignBed autoAssign) {
        System.out.println("autoAssign = " + autoAssign);

        String yxId = autoAssign.getStudentCollege();
        // 查询学员管理员
        AutoAssignBed autoAssignBed = autoAssignService.getAdminId(yxId);
        System.out.println("autoAssignBed = " + autoAssignBed);

        //查询有学生但是没有管理员的所有床位
        QueryWrapper<AutoAssignBed> queryWrapperBed = new QueryWrapper<>();

        if(oConvertUtils.isNotEmpty(autoAssign.getSchoolId())) {
            queryWrapperBed.eq("campus_id", autoAssign.getSchoolId());
        }
        if(oConvertUtils.isNotEmpty(autoAssign.getBuildingId())) {
            queryWrapperBed.eq("building_id", autoAssign.getBuildingId());
        }
        if(oConvertUtils.isNotEmpty(autoAssign.getUnitId())) {
            queryWrapperBed.eq("unit_id", autoAssign.getUnitId());
        }
        if(oConvertUtils.isNotEmpty(autoAssign.getLayerId())) {
            queryWrapperBed.eq("layer_id", autoAssign.getLayerId());
        }
        if(oConvertUtils.isNotEmpty(autoAssign.getRoomId())) {
            queryWrapperBed.eq("room_id", autoAssign.getRoomId());
        }
//        queryWrapperBed.and(queryWrapper -> queryWrapper.isNull("lb.admin_id").or().eq("lb.admin_id",""));
        List<AutoAssignBed> bedList = autoAssignService.getNullAdmin(queryWrapperBed);

        List<LwgyBaseBed> baseBedList = new ArrayList<>();

        bedList.stream().forEach(item -> {
            LwgyBaseBed lwgyBaseBed = new LwgyBaseBed();
            lwgyBaseBed.setId(item.getId());
            lwgyBaseBed.setAdminId(autoAssignBed.getAdminId());
            baseBedList.add(lwgyBaseBed);
        });
        // 更新住宿分配信息
        lwgyBaseBedService.updateBatchById(baseBedList);
        return Result.OK("操作成功!");
    }
    /******************************删除学生并且退宿 START***********************************/
    /**
     * 通过id删除学生
     *
     * @param id
     * @return
     */
    @AutoLog(value = "lwgy_base_student-通过id删除")
    @ApiOperation(value = "lwgy_base_student-通过id删除", notes = "lwgy_base_student-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {

        try {
            if (id == null) {
                return Result.error("参数id为空");
            }
            //1. 查询是否有住宿
            LwgyBaseBed lwgyBaseBed = lwgyBaseBedMapper.queryBedByStuId(id);
            //2.有住宿先退宿
            if (lwgyBaseBed != null && oConvertUtils.isNotEmpty(lwgyBaseBed.getId())) {
                LwgyHotelArrangement lwgyHotelArrangement = new LwgyHotelArrangement();
                lwgyHotelArrangement.setStudentId(id);
                lwgyHotelArrangementService.checkOutStu(lwgyHotelArrangement);
                //3. 存储到历史记录
                LwgyHotelHistory lwgyHotelHistory = new LwgyHotelHistory();
                lwgyHotelHistory.setBeforeBed(lwgyBaseBed.getId());
                lwgyHotelHistory.setBehavior("leave_bed");
                lwgyHotelHistory.setPersonId(lwgyHotelArrangement.getStudentId());
                lwgyHotelHistory.setSort("");
                lwgyHotelHistoryService.save(lwgyHotelHistory);
            }
            //4.删除学生信息
            lwgyBaseStudentService.removeById(id);
            return Result.OK("删除成功!");
        } catch (Exception e) {
            // 异常处理，返回错误信息
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除学生
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "lwgy_base_student-批量删除")
    @ApiOperation(value = "lwgy_base_student-批量删除", notes = "lwgy_base_student-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {

        try {
            if (ids == null) {
                return Result.error("参数ids为空");
            }
            List<LwgyBaseBed> lwgyBaseBed = lwgyHotelArrangementService.selectStuBedByStuId(ids);
            String bedId = "";
            LwgyHotelHistory lwgyHotelHistory;
            List<LwgyHotelHistory> arrangementList = new ArrayList<>();
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            if (lwgyBaseBed != null && !lwgyBaseBed.isEmpty()) {
                for (LwgyBaseBed item : lwgyBaseBed) {
                    bedId += item.getId() + ",";
                    lwgyHotelHistory = JSON.parseObject(JSON.toJSONString(item), LwgyHotelHistory.class);
                    lwgyHotelHistory.setPersonId(item.getStudentId());
                    lwgyHotelHistory.setBeforeBed(item.getId());
                    lwgyHotelHistory.setBehavior("leave_bed");
                    lwgyHotelHistory.setCreateBy(sysUser.getUsername());
                    arrangementList.add(lwgyHotelHistory);
                }
                //批量清空住宿
                lwgyHotelArrangementService.cleanBed(bedId);
                //批量存储退宿记录
                lwgyHotelHistoryService.saveBatch(arrangementList);
            }
            //批量删除学生
            lwgyBaseStudentService.removeByIds(Arrays.asList(ids.split(",")));
            return Result.OK("编辑成功!");
        } catch (Exception e) {
            // 异常处理，返回错误信息
            return Result.error("删除失败：" + e.getMessage());
        }
    }
    /******************************删除学生并且退宿 END***********************************/
}
